package com.yy.service.impl;

import com.yy.mapper.ArticleLogsMapper;
import com.yy.mapper.ArticleMapper;
import com.yy.pojo.ArticleLogs;
import com.yy.pojo.vo.ArticleLogsVo;
import com.yy.pojo.vo.ArticleVo;
import com.yy.service.ArticleLogsService;
import com.yy.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ArticleLogsServiceImpl implements ArticleLogsService {

    @Autowired
    private ArticleLogsMapper articleLogsMapper;
    @Autowired
    private ArticleMapper articleMapper;

    /**
     * 添加文章浏览记录
     * @param articleId
     * @return
     */
    @Override
    public Integer add(Integer articleId) {
        //获取用户ID
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        return articleLogsMapper.add(articleId,userId);
    }

    /**
     * 获取用户浏览记录
     * @return
     */
    @Override
    public List<ArticleLogsVo> list() {
        //获取用户ID
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        List<ArticleLogs> list = articleLogsMapper.list(userId);

        List<ArticleLogsVo> articleLogsVos = new ArrayList<>();
        for (ArticleLogs articleLogs : list){
            ArticleVo articleVo = articleMapper.selectById(articleLogs.getArticleId());
            ArticleLogsVo articleLogsVo = new ArticleLogsVo();
            articleLogsVo.setId(articleLogs.getId());
            articleLogsVo.setArticle(articleVo);
            articleLogsVo.setCreateTime(articleLogs.getCreateTime());
            articleLogsVos.add(articleLogsVo);
        }
        //根据创建时间倒序排序
        articleLogsVos.sort((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()));
        return articleLogsVos;
    }


}
